package br.sed.theenemy.presentation.action;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.actions.DispatchAction;

import br.sed.theenemy.business.exception.DBException;
import br.sed.theenemy.business.services.Services;
import br.sed.theenemy.business.utils.Utils;
import br.sed.theenemy.model.bean.User;
import br.sed.theenemy.presentation.EnemyConstants;
import br.sed.theenemy.presentation.UserSession;
import br.sed.theenemy.presentation.form.OptionsForm;

/**
 * 
 * @author JulioCB
 * @email jcbjulio@gmail.com
 * 
 */
public class OptionsAction extends DispatchAction {

	private static DateFormat DATE_FORMAT = new SimpleDateFormat(EnemyConstants.SIMPLE_DATE_FORMAT);
	
	// forwards
    private static final String OPTIONS_PAGE = "OptionsPage";
    private static final String LOGIN_PAGE = "LoginPage";
    
	public ActionForward unspecified(final ActionMapping mapping,
	           final ActionForm form, final HttpServletRequest request, 
	           final HttpServletResponse response) {
		OptionsForm optionsForm = (OptionsForm) form;
		
		final UserSession session = new UserSession(request, false);
        final User userLogged = session.getLoggedUser();
        
        if (userLogged == null) {
            // User not logged in, redirect to login.jsp
            return mapping.findForward(LOGIN_PAGE);
        }
        
    	optionsForm.setFirstName(userLogged.getFirstName());
    	optionsForm.setLastName(userLogged.getLastName());
    	optionsForm.setProfileImg(userLogged.getImgUrl());
    	optionsForm.setEmail(userLogged.getEmail());
    	optionsForm.setGender(userLogged.getGender());
    	optionsForm.setBornDate(DATE_FORMAT.format(userLogged.getBornDate()));
        // User logged redirect to options
        return mapping.findForward(OPTIONS_PAGE);
        
	}
	
	@SuppressWarnings("deprecation")
    public ActionForward edit(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request, 
            final HttpServletResponse response) {
		OptionsForm optionsForm = (OptionsForm) form;
		Services services = Services.getInstance();
		
		final UserSession session = new UserSession(request, false);
        final User userLogged = session.getLoggedUser();
        
        if (userLogged == null) {
            // User not logged in, redirect to login.jsp
            return mapping.findForward(LOGIN_PAGE);
        }
        
        final ActionErrors errors = new ActionErrors();
        errors.add(form.validate(mapping, request));
        if (!errors.isEmpty()) {
            saveErrors(request, errors);
            return forwardToOptionsPage(mapping, optionsForm, userLogged, 1);
        }

        String dateStr = optionsForm.getBornDate();
		Date bornDate = null;
		try {
			bornDate = DATE_FORMAT.parse(dateStr);
		} catch (ParseException e1) {
		    return mapping.findForward(EnemyConstants.ERROR_PAGE);
		}
		Date minimumAge = new Date();
		int year = minimumAge.getYear()-18;
		minimumAge.setYear(year);
		if(bornDate.after(minimumAge)){
		    errors.add("bornDate", new ActionMessage("form.options.borndate.minimumage"));
		    saveErrors(request, errors);
		    return forwardToOptionsPage(mapping, optionsForm, userLogged, 1);
		}
		
		
		String gender;
		if("M".equals(optionsForm.getGender())){
			gender = "M";
		}else if("F".equals(optionsForm.getGender())){
			gender = "F";
		}else{
		    return mapping.findForward(EnemyConstants.ERROR_PAGE);
		}
        
		Long userId = userLogged.getId();
		String firstName = optionsForm.getFirstName();
		String lastName = optionsForm.getLastName();
		
		if(Utils.isNullOrEmpty(firstName)||Utils.isNullOrEmpty(lastName)){
		    return mapping.findForward(EnemyConstants.ERROR_PAGE);
		}
		
		try {
            services.updateUser(userId, firstName, lastName, gender, bornDate);
        } catch (DBException e) {
            return mapping.findForward(EnemyConstants.ERROR_PAGE);
        }
		//setting new values on the session
		userLogged.setFirstName(firstName);
		userLogged.setLastName(lastName);
		userLogged.setGender(gender);
		userLogged.setBornDate(bornDate);
		return forwardToOptionsPage(mapping, optionsForm, userLogged, 1);
	}
	
	public ActionForward changePassword(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request, 
            final HttpServletResponse response) {
		OptionsForm optionsForm = (OptionsForm) form;
		Services services = Services.getInstance();
		
		final UserSession session = new UserSession(request, false);
        final User userLogged = session.getLoggedUser();
        
        if (userLogged == null) {
            // User not logged in, redirect to login.jsp
            return mapping.findForward(LOGIN_PAGE);
        }
        
        final ActionErrors errors = new ActionErrors();
        errors.add(form.validate(mapping, request));
        if (!errors.isEmpty()) {
            saveErrors(request, errors);
            return forwardToOptionsPage(mapping, optionsForm, userLogged, 2);
        }
        
        String password = optionsForm.getPassword();
    	String newPassword = optionsForm.getNewPassword();
    	String confirmNewPassword = optionsForm.getConfirmNewPassword();
    	
    	if(!(password==null || newPassword==null || confirmNewPassword==null)){
    		if(newPassword.equals(confirmNewPassword)){
    			String passwordMD5 = Utils.MD5(password);
    			if(userLogged.getPass().equals(passwordMD5)){
    				String newPasswordMD5 = Utils.MD5(optionsForm.getNewPassword());
    				try {
                        services.changePassword(userLogged.getId(), newPasswordMD5);
                    } catch (DBException e) {
                        return mapping.findForward(EnemyConstants.ERROR_PAGE);
                    }
    			}	
    		}
    	}
    	optionsForm.setFirstName(userLogged.getFirstName());
    	optionsForm.setLastName(userLogged.getLastName());
    	optionsForm.setEmail(userLogged.getEmail());
    	optionsForm.setBornDate(DATE_FORMAT.format(userLogged.getBornDate()));
    	optionsForm.setGender(userLogged.getGender());
		optionsForm.setPassword("");
		optionsForm.setNewPassword("");
		optionsForm.setConfirmNewPassword("");
		return forwardToOptionsPage(mapping, optionsForm, userLogged, 2);
	}
	
	public ActionForward changeImage(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request, 
            final HttpServletResponse response) {
        OptionsForm optionsForm = (OptionsForm) form;
        Services services = Services.getInstance();
        
        final UserSession session = new UserSession(request, false);
        final User userLogged = session.getLoggedUser();
        
        if (userLogged == null) {
            // User not logged in, redirect to login.jsp
            return mapping.findForward(LOGIN_PAGE);
        }
        
        if(!form.validate(mapping, request).isEmpty()){
            return mapping.findForward(EnemyConstants.ERROR_PAGE);
        }
        
        String imgUrl = optionsForm.getProfileImg();
        
        if(Utils.isNullOrEmpty(imgUrl)){
            return mapping.findForward(EnemyConstants.ERROR_PAGE);
        }
        
        try {
            services.changeImage(userLogged.getId(), imgUrl);
        } catch (DBException e) {
            return mapping.findForward(EnemyConstants.ERROR_PAGE);
        }
        
        userLogged.setImgUrl(imgUrl);
        return forwardToOptionsPage(mapping, optionsForm, userLogged, 3);
	}
	
	private ActionForward forwardToOptionsPage(ActionMapping mapping, OptionsForm form, User userLogged, int mode){
	    if(mode==2 || mode==3){
    	    form.setFirstName(userLogged.getFirstName());
    	    form.setLastName(userLogged.getLastName());
    	    form.setEmail(userLogged.getEmail());
            form.setBornDate(DATE_FORMAT.format(userLogged.getBornDate()));
            form.setGender(userLogged.getGender());
	    }
        form.setPassword("");
        form.setNewPassword("");
        form.setConfirmNewPassword("");
	    
        form.setProfileImg(userLogged.getImgUrl());
        
	    return mapping.findForward(OPTIONS_PAGE);
	}
}
